<template>
	<view class="wrap">
		<view class="search">
			<u-search placeholder="请输入标题" v-model="query.title" height="80" @custom="search" @search="search"></u-search>
			<u-dropdown ref="uDropdown" :close-on-click-mask="uDropdown.mask" :activeColor="uDropdown.activeColor" :borderBottom="uDropdown.borderBottom">
				<u-dropdown-item v-model="query.isRepeat" @change="isRepeatChange"
					:title="uDropdown.isRepeatTitle" :options="uDropdown.isRepeatOptions"></u-dropdown-item>
				<u-dropdown-item v-model="query.status" @change="statusChange"
					:title="uDropdown.statusTitle" :options="uDropdown.statusOptions"></u-dropdown-item>	
			</u-dropdown>
		</view>
		<scroll-view class="scroll-list" scroll-y="true" style="width: 100%; height: 87%; margin-top: 5rpx;margin-bottom: 5rpx;" @scrolltolower="loadMore">
			<view>
				<u-swipe-action v-for="(item, index) in list" :show="item.show" :key="item.id" :index="index" 
					:options="dynamicGetSwipeActionOptions(item)" @click="click" 
					@open="open" @close="close" class="uni-list" style="margin-top: 10rpx;margin-bottom: 10rpx;">
					<view @click="toView(item.id)">
						<u-row style="margin: 20rpx;">
							<u-col span="9" class="ellipsisContent" style="font-weight: bold;">
								{{item.title}}
							</u-col>
							<u-col span="3" style="text-align: right;">
								<text :style="{'border-color': getTextColorByValue(item.status),color: getTextColorByValue(item.status)}">
									{{statusTranslate(item.status)}}
								</text>
							</u-col>
						</u-row>
						<u-row style="margin: 10rpx;color:gray;">
							<u-col span="12">
								<font v-if="item.description!=null && item.description!=''">{{item.description}}</br></br></font>
								{{item.startTime}} ~ {{item.endTime}}
							</u-col>
						</u-row>
					</view>
				</u-swipe-action>
			</view>
			<view class="loadmore" @click="loadMore">
				<u-loadmore :status="loadStatus"></u-loadmore>
			</view>
		</scroll-view>
		<view v-if="hasPermission('wechatMeeting_add')" class="btn-plus" @click="toAdd">
			<u-icon name="plus-circle-fill" size="90" color="#3d87ff"></u-icon>
		</view>
		<view v-if="hasPermission('wechatMeeting_quickCreate')" class="btn-plus" style="bottom: 150rpx;" @click="createQuickMeeting">
			<u-icon name="grid" size="90" color="#3d87ff"></u-icon>
		</view>
	</view>
</template>
<script>
	import { invokeWxJsApi,isAllowAlert } from '@/common/wx.jssdk.js'
	
	export default {
		components: {
			
		},
		data() {
			return {
				query: {
					current: 1,
					size: 20,
					title: null
				},
				list: [],
				count: 0,
				loadStatus: 'loadmore',
				arrow: false,
				uDropdown: {
					mask: true,
					borderBottom: false,
					activeColor: '#2979ff',
					isRepeatOptions: [],
					isRepeatTitle: '会议类型',
					statusOptions: [],
					statusTitle: '状态',
				}
			}
		},
		computed:{
			
		},
		onLoad() {
			this.loadList();
			this.initStatus();
			this.initIsRepeat();
		},
		onShow() {
			if(uni.getStorageSync("refreshWecahtMeetingList") === true){
				uni.removeStorageSync("refreshWecahtMeetingList");
				this.search();
			}
		},
		created() {
			
		},
		onReady() {
			
		},
		mounted(){
			// console.log("mounted引入",uni.fjutWeixin);
		},
		computed: {
			isRepeatTranslate: function(){
				return (isRepeat) => {
					isRepeat = isRepeat + '';
					let dictData = this.uDropdown.isRepeatOptions.find(e => e.value == isRepeat);
					let isRepeatName = '';
					if(dictData){
						isRepeatName = dictData.label;
					}
					return isRepeatName || isRepeat;
				}
			},
			statusTranslate: function(){
				return (status) => {
					status = status + '';
					let dictData = this.uDropdown.statusOptions.find(e => e.value == status);
					let statusName = '';
					if(dictData){
						statusName = dictData.label;
					}
					return statusName || status;
				}
			}
		},
		methods: {
			initIsRepeat(){
				let vm = this;
				this.$u.api.dictBizData({
					code: 'wechat_is_repeat'
				}).then(res => {
					let optionList = [];
					let option = {
						'label': '全部',
						'value': ''
					}
					optionList.push(option);
					res.data.forEach((item) => {
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.uDropdown.isRepeatOptions = optionList;
				});
			},
			initStatus(){
				let vm = this;
				this.$u.api.dictBizData({
					code: 'wechat_meeting_status'
				}).then(res => {
					let optionList = [];
					let option = {
						'label': '全部',
						'value': ''
					}
					optionList.push(option);
					res.data.forEach((item) => {
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.uDropdown.statusOptions = optionList;
				});
			},
			isRepeatChange(index){
				this.list = [];
				this.query.current = 1;
				this.query.isRepeat = index;
				this.uDropdown.isRepeatTitle=(index===''?'会议类型':this.getOptionLabel(this.uDropdown.isRepeatOptions,index));
				this.loadList();
			},
			statusChange(index){
				this.list = [];
				this.query.current = 1;
				this.query.status = index;
				this.uDropdown.statusTitle=(index===''?'状态':this.getOptionLabel(this.uDropdown.statusOptions,index));
				this.loadList();
			},
			dynamicGetSwipeActionOptions: function(item){
				let uSwipeActionOptions = [];
				const { status,startTime, createUser } = item;
				if (this.hasPermission('wechatMeeting_edit') 
					&& new Date(startTime).getTime() > new Date().getTime() 
					&& status === 1 
					&& createUser === this.vuex_userId) {
					uSwipeActionOptions.push({
						text: '编辑',
						style: {
							backgroundColor: '#079cff'
						},
						action: 'edit'
					});
				}
				if (this.hasPermission('wechatMeeting_delete')) {
					uSwipeActionOptions.push({
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						},
						action: 'delete'
					});
				}
				if (this.hasPermission('wechatMeeting_cancel') 
					&& new Date(startTime).getTime() > new Date().getTime() 
					&& status === 1 
					&& createUser === this.vuex_userId) {
					uSwipeActionOptions.push({
						text: '取消',
						style: {
							backgroundColor: '#aa55ff'
						},
						action: 'cancel'
					});
				}
				
				//进入会议 1 待开始 2 会议中
				if(this.hasPermission('wechatMeeting_enter') && (status === 1 || status === 2)){
					uSwipeActionOptions.push({
						text: '进入',
						style: {
							backgroundColor: '#ffd199'
						},
						action: 'enterMeeting'
					});
				}
				return uSwipeActionOptions;
			},
			getFontColorByValue: function(isRepeat) {
				let color = '#606266';
				return color;
			},
			getTextColorByValue: function(status){
				let color = '#606266';
				if(status == '1'){
					// 1 待开始
					color = '#19be6b';
				}else if(status == '2'){
					// 2 会议中
					color = '#2979ff';
				}else if(status == '3'){
					// 3 已结束
					color = '#ff9900';
				}else if(status == '4'){
					// 4 已取消
					color = '#fa3534';
				}else if(status == '4'){
					// 5 已过期
					color = '#fa7468';
				}
				return color;
			},
			loadList() {
				let vm = this;
				this.$u.api.wechat.wechatMeeting.list(this.query).then(res => {
					if (!res.data || !res.data.records || res.data.records == 0) {
						vm.loadStatus = "nomore";
						return;
					}
					vm.list = vm.list.concat(res.data.records);
					vm.list.forEach((item) => {
						item.show = false;
					})
					vm.count = res.total;
					vm.query.current = res.data.current;
					vm.query.size = res.data.size;
					vm.loadStatus = "loadmore";
					// console.log("loadList加载完毕...");
				});
			},
			loadMore() {
				this.loadStatus = "loading";
				setTimeout(() => {
					this.query.current += 1;
					this.loadList();
				}, 100);
			},
			search() {
				this.list = [];
				this.query.current = 1;
				this.loadList();
			},
			click(rowIndex, btnIndex) {
				let item = this.list[rowIndex];
				let swipeActionOptions = this.dynamicGetSwipeActionOptions(item);
				let { action } = swipeActionOptions[btnIndex];
				if (action == 'edit') {
					this.navTo('form?id=' + item.id + "&mode=edit");
				} else if (action == 'delete') {
					this.handleDelete(item.id, rowIndex);
				} else if (action == 'cancel') {
					this.handleCancel(item.id, rowIndex);
				} else if(action == 'enterMeeting'){
					this.enterMeeting(item.meetingid);
				}
			},
			toView(id){
				if(this.hasPermission('wechatMeeting_view')){
					this.navTo('form?id=' + id + '&mode=view');
				}
			},
			toAdd() {
				this.navTo('form?mode=add');
			},
			/**
			 * 打开一个swipeAction的同时，需要自动关闭其他的swipeAction
			 * 
			 * @param {Object} index
			 */
			open(index) {
				this.list[index].show = true;
				//下面这行代码不可少，有点神奇
				this.$set(this.list, index, this.list[index]);
				this.list.map((val, idx) => {
					if (index != idx) {
						this.list[idx].show = false;
					}
				})
			},
			close(index) {
				this.list[index].show = false;
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			handleDelete(id, rowIndex) {
				let self = this;
				uni.showModal({
					title: '提示',
					content: '确定将选择数据删除？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							self.$u.api.wechat.wechatMeeting.remove({
								"ids": id
							}).then(res => {
								if (res.success) {
									self.list[rowIndex].show = false;
									//下面这行代码不可少，有点神奇
									self.$set(self.list, rowIndex, self.list[rowIndex]);
									self.$u.toast('删除成功！');
									self.list.splice(rowIndex, 1);
								}
							});
						}
					}
				});
			},
			handleCancel(id, rowIndex) {
				let self = this;
				uni.showModal({
					title: '提示',
					content: '确定取消？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							self.$u.api.wechat.wechatMeeting.cancel({
								"id": id
							}).then(res => {
								if (res.success) {
									self.list[rowIndex].show = false;
									//status: 1(待开始)、2(会议中)、3(已结束)、4(已取消)、5(已过期)
									self.list[rowIndex].status = 4;
									//下面这行代码不可少，有点神奇
									self.$set(self.list, rowIndex, self.list[rowIndex]);
									self.$u.toast('取消成功！');
								}
							});
						}
					}
				});
			},
			/**
			 * 创建快速会议
			 */
			invokeStartMeetingApi() {
				uni.fjutWeixin.invoke('startMeeting', {}, function(res) {
					if(isAllowAlert()){
						alert("调试显示 invokeStartMeetingApi:::" + JSON.stringify(res));
					}
					if (res.err_msg == "startMeeting:ok") {
						//目前是回调没有meetingId返回！
						console.log("会议开始...");
					}
				});
			},
			/**
			 * 触发创建快速会议
			 */
			createQuickMeeting() {
				let jsApiList = ['startMeeting'];
				invokeWxJsApi(jsApiList,this.invokeStartMeetingApi);
			},
			/**
			 * 进入会议

			 * @param {Object} meetingId
			 */
			invokeEnterMeetingApi(meetingId) {
				uni.fjutWeixin.invoke('startMeeting', {
					"meetingId": meetingId,
				}, function(res) {
					if(isAllowAlert()){
						alert("调试显示 invokeEnterMeetingApi:::" + JSON.stringify(res));
					}
					if (res.err_msg == "startMeeting:ok") {
						meetingId = res.meetingId;
					}
				});
			},
			/**
			 * 触发进入会议
			 * @param {Object} meetingId
			 */
			enterMeeting(meetingId) {
				console.log("meetingId:%s",meetingId);
				let jsApiList = ['startMeeting'];
				invokeWxJsApi(jsApiList,this.invokeEnterMeetingApi,meetingId);
			}
		}
	}
</script>

<style lang="scss">
	@import '../../../common/uni.css';
	
	page {
		background-color: #f5f5f5;
	}
	
	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top) - var(--window-bottom)); // 视高 - 内容区顶部 - 内容区底部
		width: 100%;
	}
	
	.search{
		height:90px;
		background-color: #ffffff;
		background-size: 450px;
	}
	
	.fontStyle{
		font-weight: bold;
	}
	
	.ellipsisContent {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.textBlock {
		padding: 3rpx;
		border-width: 1px;
		border-style: solid;
	}
</style>